<template>
  <el-upload
    class="upload-el"
    :show-file-list="false"
    :file-list="fileList"
    :http-request="handleCustomUpload"
    :before-upload="beforeUpload"
    accept="image/*">
    <slot></slot>
  </el-upload>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BaseAPI } from '@/api/base';
  import { ElMessage, UploadRawFile } from 'element-plus';
  import { cropImageStore } from '@/store/cropImage';
  const cropStore = cropImageStore();

  const fileList = ref<any>([]);

  const emit = defineEmits(['upLoadImg']);

  // 自定义上传方法
  const handleCustomUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    const blob = new Blob([file]);
    emit('upLoadImg', {
      blob,
    });
    cropStore.setUpImage(blob);
  };

  // 文件上传前的验证方法
  const beforeUpload = (file: UploadRawFile) => {
    // 定义最大文件大小 (20MB)
    const maxSize = 20 * 1024 * 1024;
    // 检查文件大小
    if (file?.size > maxSize) {
      ElMessage.error('The file size cannot exceed 20M');
      return false;
    }
    // 验证通过，继续上传
    return true;
  };
</script>

<style scoped lang="scss">
  .upload-el {
    line-height: 0;
  }
  :deep(.el-upload) {
    padding: 0 !important; /* 清除默认内边距（通常是 15px） */
    height: auto !important; /* 高度由内容决定 */
    min-height: auto !important; /* 清除可能的最小高度 */
  }
</style>
